package cn.com.ibjj.u10010;

import com.alibaba.fastjson.JSON;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.util.*;

public class Main {
    static String numberYouLike = "";
    static boolean isCmd = false;  //判断是否需要人工交互
    static boolean ckGoodNumber = false;   //是否把好号码挑出来
    static boolean isCkAllGoodNumber = false;   //按12、13、14、。。。全部挑一次好号码
    static HashMap queryResult = new HashMap(); //存放查询结果的提示信息
    static ArrayList<NumberDecompress> incData = new ArrayList<NumberDecompress>();    //存放全量的查询结果
    static ArrayList<NumberDecompress> goodData = new ArrayList<NumberDecompress>();   //存放好号码的查询结果

    public static void main(String[] args) throws IOException, InterruptedException {
        if (args.length == 0) {
            System.out.println("****查询联通10010网站北京地区可用号码****");
        } else {
            numberYouLike = args[0];
            if (args.length == 2) {
                ckGoodNumber = true;
                numberYouLike = args[1];
            }
            if (args.length == 3) {
                ckGoodNumber = true;
                numberYouLike = args[2];
                isCkAllGoodNumber = true;
            }
            isCmd = true;
        }
        if (!isCkAllGoodNumber)
            searchNumber(numberYouLike, "11");
        else
            searchAllNumber();
    }

    private static void searchAllNumber() throws IOException, InterruptedException {
        for (int p = 11; p < 50; p++) {
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 10; j++) {
                    String q = Integer.toString(i) + Integer.toString(j) + Integer.toString(j) + Integer.toString(i);
                    try {
                        searchNumber(q, Integer.toString(p));
                    } catch (Exception e) {
                        System.out.println(Integer.toString(p) + ": 省码不存在");
                    }
                    Thread.sleep(100);
                }
            }
        }
        if (goodData.size() == 0) {
            System.out.println("没找到好号码");
            return;
        }
        //最后打印下最后的结果
        //排序
        Collections.sort(goodData);
        System.out.println("------------------------");
        System.out.println(goodData.get(0).getTitleString());
        for (NumberDecompress a : goodData) {
            System.out.println(a.getCsvString());
        }
        System.out.println("------------------------");
        Iterator iter = queryResult.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            String val = (String) entry.getValue();
            System.out.println(key + ":" + val);
        }
        System.out.println("------------------------");
        System.out.println("共找到好号码" + goodData.size() + "个");
    }

    private static void searchNumber(String queryNumber, String prov) throws IOException {
        //初始化容器。如果isCkAllGoodNumber,则不复位gooddata
        incData.clear();
        if (!isCkAllGoodNumber) goodData.clear();
        //查询参数初始化
        HashMap p = new HashMap();
        p.put("province", prov);
        p.put("cityCode", "");
        p.put("searchType", "02");
        p.put("sortType", "numDesc");
        p.put("Show4GNum", "TRUE");
        p.put("configKey", "ZJ2t2ofiM9Ikpv4JE8Dctg%3D%3D");
        //如果有人工交互，则只执行一次，如果没有人工交互，则一直执行下去，除非按回车键
        //while (!isCmd && !(numberYouLike = readString("输入你喜欢的数字(回车键退出)：")).isEmpty()) {
        while (true) {
            if (!isCmd) queryNumber = readString("输入你喜欢的数字(回车键退出, *代表任意字符)：");
            incData.clear();
            if (queryNumber.isEmpty()) break; //回车退出
            if (queryNumber.equals("*")) queryNumber = "";
            p.put("searchValue", queryNumber); // Search String
            Connection.Response response = null;
            response = Jsoup.connect("http://num.10010.com/NumApp/chseNumList/serchNums").ignoreContentType(true)
                    .data(p).execute();
            String jsonR = response.body();
            //===下面对查询结果进行结构化处理
            JSONResult data = (JSONResult) JSON.parseObject(jsonR, JSONResult.class);
            String[] numMemoList = new String[data.numMemoList.size()];
            numMemoList = data.numMemoList.toArray(numMemoList);
            String[] dataCompress = new String[data.getMoreNumArray().size()];
            dataCompress = data.moreNumArray.toArray(dataCompress);

            for (int i = 0; i < dataCompress.length; i += 8) {
                NumberDecompress numberDecompress = new NumberDecompress();
                numberDecompress.NumID = dataCompress[i] + "";
                numberDecompress.NumPreFee = (Integer.parseInt(dataCompress[i + 1]) * 100) + "";
                numberDecompress.NumMemo = numMemoList[Integer.parseInt(dataCompress[i + 2])];
                numberDecompress.NumLevel = dataCompress[i + 3] + "";
                numberDecompress.City = dataCompress[i + 4] + "";
                numberDecompress.NiceRuleTag = dataCompress[i + 5] + "";
                numberDecompress.numMonFeeLimit = dataCompress[i + 6] + "";
                numberDecompress.numMonLimit = dataCompress[i + 7] + "";
                incData.add(numberDecompress);
            }
            //输出结果到控制台
            if (incData.size() > 0) {
                Collections.sort(incData);
                int goodNumCout = 0;
                System.out.println(incData.get(0).getTitleString());
                for (NumberDecompress a : incData) {
                    if (ckGoodNumber) {
                        if (!isGoodNumber(a.getNumID())) {
                            continue;
                        }
                        goodData.add(a);
                        goodNumCout++;
                    }
                    System.out.println(a.getCsvString());
                }
                System.out.printf("%s : 共查到 %d 条记录", queryNumber, incData.size());
                if (ckGoodNumber) System.out.printf("其中好号码有 %d 个（第8、11位相同，第9、10位相同）\n", goodNumCout);
                queryResult.put(queryNumber, "\t共\t" + incData.size() + "\t好的\t" + goodNumCout);
            } else {
                System.out.println(queryNumber + "\t没查到匹配的号码");
            }
            if (isCmd) break;   //命令行运行，直接退出，不需要再次查询
        }
    }

    public static String readString(String prompt) {
        Scanner scanner = new Scanner(System.in);
        System.out.print(prompt);
        return scanner.nextLine();
    }

    private static boolean isGoodNumber(String number) {
        if (number.length() != 11) return false;    //不是手机号码，直接返回False
        //第8位与第11位一样，第9位与第10位一样，认为是好号码
        if (number.charAt(7) == number.charAt(10) && number.charAt(8) == number.charAt(9)) return true;
        return false;
    }
}